package com.cloudbroker.bcs.common.resource;

import static com.cloudbroker.bcs.common.util.ReflectionUtil.*;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

/**
 * Created by xuyn15828 on 2016/5/24.
 *  为了防止因为ResourceLoaderAware导致spring的resourceLoader被注入,进行控制
 */
public class DavReloadableResourceBundleMessageSource extends ReloadableResourceBundleMessageSource {
    protected Boolean useSelfResource;
    private static final String SPRING = "spring";
    private ResourceLoader resourceLoader = new DefaultResourceLoader();
    private static final Logger logger = LoggerFactory.getLogger(DavReloadableResourceBundleMessageSource.class);

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        if( useSelfResource ) {
            if( shouldBuildDefaultResourceLoader(resourceLoader) ) {
                resourceLoader = new DefaultResourceLoader();
            }
            setSuperResourceLoader(resourceLoader);
        } else {
            setSuperResourceLoader(resourceLoader);
        }
    }

    private boolean shouldBuildDefaultResourceLoader(ResourceLoader resourceLoader) {
        boolean currentUseSelfResourceLoader = null != this.resourceLoader &&
                !StringUtil.containsIgnoreCase(this.resourceLoader.getClass().getName() , SPRING);
        if( resourceLoader != null ) {
            String clazzName = resourceLoader.getClass().getName();
            //如果新resourceLoader不是spring产生的
            //并且当前使用的resourceLoader也是自己的,则进行打印替换日志并替换
            logger.info(">>>>>> resourceLoader conflict and repeat from" +
                    getClassName(this.resourceLoader) + " to " + getClassName(resourceLoader));
            return !StringUtil.containsIgnoreCase(clazzName, SPRING) && currentUseSelfResourceLoader;
        }
        return !currentUseSelfResourceLoader;
    }

    private void setSuperResourceLoader(ResourceLoader resourceLoader) {
        boolean isSelfResourceLoader = resourceLoader != null &&
                !StringUtil.containsIgnoreCase(getClassName(resourceLoader) , SPRING);
        if( isSelfResourceLoader || null == this.resourceLoader ) {
            this.resourceLoader = resourceLoader;
            super.setResourceLoader(resourceLoader);
        }
    }

    public ResourceLoader getResourceLoader() {
        return this.resourceLoader;
    }

    public Boolean isUseSelfResource() {
        return useSelfResource;
    }

    public void setUseSelfResource(Boolean useSelfResource) {
        this.useSelfResource = ValueUtil.getBoolean(useSelfResource , false);
    }
}
